package com.suxin.ratelimit.v2.aop;

import com.suxin.ratelimit.v2.RateLimit;
import com.suxin.ratelimit.v2.exception.LimitRestException;
import com.suxin.ratelimit.v2.handler.Rate;
import com.suxin.ratelimit.v2.handler.RateLimitHandler;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;

import javax.annotation.Resource;

/**
 * @author Tang
 * @classname DefaultMethodInterceptor
 * @description [  ]
 * @date 2022/2/9 17:07
 */
public class DefaultMethodInterceptor implements MethodInterceptor {

    @Resource
    private RateLimitHandler rateLimitHandler;

    @Override
    public Object invoke(MethodInvocation invocation) throws Throwable {
        RateLimit annotation = invocation.getMethod().getAnnotation(RateLimit.class);
        boolean result = rateLimitHandler.handler(
                new Rate(annotation.duration(), annotation.limit(), annotation.unit(), annotation.type())
        );
        if (result) {
            throw new LimitRestException("请求被限流了~~");
        }else {
            return invocation.proceed();
        }
    }

}